<template>
  <el-container class="questAddForm-box">
    <el-header>
      <el-row :gutter="10">
        <el-col :span="6">
          <span @click="() => {this.$router.go(-1)}" class="font-blue my-btn">返回上级</span>
        </el-col>
        <el-col :push="3" :span="10"><span>{{pageTitle}}</span></el-col>
      </el-row>
    </el-header>
    <el-main style="padding: 0 200px;">
      <el-form
        ref="addform"
        :model="formData"
        label-width="100px"
        size="mini"
        :rules="rules"
        >

        <el-form-item label="难易：" prop="degree">
          <el-radio-group v-model="formData.degree">
            <el-radio label="easy">简单</el-radio>
            <el-radio label="medium">中等</el-radio>
            <el-radio label="hard">困难</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题型：" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="single">单选题</el-radio>
            <el-radio label="multiple">多选题</el-radio>
            <el-radio label="judge">判断题</el-radio>
            <el-radio label="text">填空</el-radio>
            <el-radio label="composite">问答</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文献：" class="mx-width" prop="literature">
          <el-input type="textarea" v-model="formData.literature" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="考试人群：" class="mx-width" prop="intend">
          <el-input v-model="formData.intend" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="分类：" prop="class">
          <el-select v-model="formData.class" placeholder="请选择分类">
            <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="内容：" class="mx-width" prop="content">
          <el-input type="textarea" v-model="formData.content" placeholder="请输入内容" @blur="contentBlur"></el-input>
        </el-form-item>

        <el-form-item label="图片：" prop="images" >
          <PhotoUpload v-model="formData.images"></PhotoUpload>
        </el-form-item>
        <!-- 题型的区分开始 -->
        <!-- 选择题开始 -->
        <template v-if="testType == 1">
          <el-form-item label="选项：" prop="options">
            <el-row :key="index" v-for="(item, index) in formData.options">
              <el-col :span="1">
                <span @click="FoptionsClick(index)" :class="[item.selected ? 'el-icon-circle-check' : 'el-icon-circle-check-outline', 'font-blue']"></span>
              </el-col>
              <el-col :span="20">
                <el-input v-model="formData.options[index].text" placeholder="请输入内容">
                  <template slot="append"><el-button @click="deloptions(index)"><span class="el-icon-close"></span></el-button></template>
                </el-input>
              </el-col>
            </el-row>
            <!-- <el-row v-if="formData.type == '多选题'"> -->
            <el-row>
              <el-col :span="20" :push="1">
                <el-button type="primary" @click="addoptions">+ 添加选项</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <!-- 选择题结束 -->
        <!-- 判断题开始 -->
        <template v-if="testType == 2">
          <el-form-item label="答案：" prop="judgeAnswer">
            <el-radio-group v-model="formData.judgeAnswer">
              <el-radio v-for="(item, index) in judgeOptions" :key="index" :label="item.value">{{item.text}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <!-- 判断题结束 -->
        <!-- 填空题开始 -->
        <template v-if="testType == 3">
          <el-form-item label="答案：" prop="fillAnswers">
            <el-row class="font-blue">请在内容栏里使用 _ 下划线 来表示所要填写的空</el-row>
            <el-row :key="index" v-for="(item, index) in formData.fillAnswers">
              <el-col :span="20">
                <el-input v-model="formData.fillAnswers[index].text" :placeholder="'答案' + (index + 1)"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <!-- 填空题结束 -->
        <!-- 问答题开始 -->
        <template v-if="testType == 4">
          <el-form-item label="答案：" prop="QAnswer">
            <el-input type="textarea" v-model="formData.QAnswer" placeholder="请输入内容"></el-input>
          </el-form-item>
        </template>
        <!-- 问答题结束 -->
        <!-- 题型的区分结束 -->

        <el-form-item label="解析：" class="mx-width" prop="analysis">
          <el-input type="textarea" v-model="formData.analysis" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="标签：" prop="tag">
          <el-select multiple collapse-tags v-model="formData.tag" placeholder="请选择标签">
            <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="save('numberValidateForm')">保存</el-button>
          <el-button @click="() => {this.$refs.addform.resetFields()}">重置</el-button>
        </el-form-item>

      </el-form>
    </el-main>
  </el-container>
</template>

<script>
const judgeOptions = [{
  text: '正确',
  value: 'yes'
}, {
  text: '错误',
  value: 'no'
}]

import PhotoUpload from '@/components/PhotoUpload'

export default {
  name: 'QuestAddForm',
  components: {
    PhotoUpload
  },
  mounted () {
    this._questionid = this.$route.params.id
    if (this._questionid || this._questionid == 0) { // 编辑表单
      this._pageType = 'edit'
      // 获取此表单数据并初始化
      this.$API.getQuestion(this._questionid)
      .then(data => {
        console.log(data)
        this._initForm(data)
      })
    } else { // 新增表单
      this._pageType = 'add'
    }

    this.$API.getAllQuestClass()
    .then(data => {
      this.classOptions = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })

    this.$API.getAllLabellist('question')
    .then(data => {
      this.tagOptions = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
  },
  data () {
    return {
      rules: {
        degree: [{ required: true, message: '请选择难度'}],
        type: [{ required: true, message: '请选择题型'}],
        class: [{ required: true, message: '请选择分类'}],
        content: [{ required: true, message: '请填入题干'}]
      },
      _pageType: '',
      _questionid: '',
      formData: {
        degree: '',
        type: '',
        literature: '',
        intend: '',
        class: '',
        content: '',
        images: [],
        options: [{
          text: '',
          selected: false
        }, {
          text: '',
          selected: false
        }, {
          text: '',
          selected: false
        }, {
          text: '',
          selected: false
        }],
        fillAnswers: [],
        QAnswer: '',
        analysis: '',
        tag: '',
        judgeAnswer: 'yes'
      },
      judgeOptions,
      classOptions: [],
      tagOptions: []
		}
  },
  computed: {
    testType () {
      switch (this.formData.type) {
        case 'single':
        case 'multiple':
          return 1;
        case 'judge':
          return 2;
        case 'text':
          return 3;
        case 'composite':
          return 4;
        default: 0;
      }
    },
    pageTitle () {
      return this.$route.name
    }
  },
  methods: {
    contentBlur () {
      if (this.testType == 3) {
        this.formData.fillAnswers = []
        let c = this.formData.content
        let find = c.match(/_/gim)
        find.forEach(item => {
          this.fill_addoptions()
        })
      }
    },
    FoptionsClick (index) {
      if (this.formData.type == 'single') {
        this.FSoptionsClick(index)
      } else if (this.formData.type == 'multiple') {
        this.FMoptionsClick(index)
      }
    },
    FSoptionsClick (index) { // 单选事件
      this.formData.options = this.formData.options.map((item, idx) => {
        if (idx == index) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })
    },
    FMoptionsClick (index) { // 多选事件
      this.formData.options = this.formData.options.map((item, idx) => {
        if (idx == index) {
          item.selected = !item.selected;
        }
        return item;
      })
    },
    save () {
      let form = this.formData
      let params = {}
      params.difficulty = form.degree;
      params.type = form.type;
      params.question_category_id = form.class;
      params.title = form.content;
      params.note = form.analysis;
      params.literature = form.literature;
      params.intend = form.intend;
      params.tags = form.tag.map(item => {
        return {id: item}
      });
      params.images = form.images.map(item => {
        return {image: item}
      });

      switch (this.testType) {
        case 1: // 选择题
          params.content = form.options.map(item => {
            return {text: item.text, answer: item.selected}
          })
          break;
        case 2: // 判断题
          params.content = {answer: form.judgeAnswer}
          break;
        case 3: // 填空题
          params.content = form.fillAnswers
          break;
        case 4: // 问答题
          params.content = {answers: form.QAnswer}
          break;
        default: ;
      }

      if (this._pageType == 'edit') {
        this.$API.updateQuestion(this._questionid, params)
        .then(data => {
          this.$message({
            message: `修改题目成功`,
            type: `success`,
            duration: 2000
          })
          this.$router.replace('/home/questList')
        })
      } else {
        this.$API.addQuestion(params)
        .then(data => {
          this.$message({
            message: `新增题目成功`,
            type: `success`,
            duration: 2000
          })
          this.$router.replace('/home/questList')
        })
      }
    },
    addoptions () {
      this.formData.options.push({
        text: '',
        selected: false
      })
    },
    deloptions (index) {
      this.formData.options.splice(index, 1)
    },
    fill_addoptions () {
      this.formData.fillAnswers.push({
        text: ''
      })
    },
    _initForm (data) { // 只在表单为编辑表单时在mounted生命周期使用
      let { difficulty, type, question_category_id, title, note, literature, intend, tag, content, images, tags } = data

      let fd_content = content
      let fd = { // 表单初始值
        degree: difficulty,
        type,
        class: question_category_id,
        content: title,
        analysis: note,
        literature,
        intend,
        tag: tags.map(item => item.id),
        images: images.map(item => item.image)
      }

      switch (type) {
        case 'single':
        case 'multiple':
          this.formData = Object.assign({}, this.formData, fd, {options: fd_content.map(item => { return { text: item.text, selected: item.answer } })})
          break;
        case 'judge':
          this.formData = Object.assign({}, this.formData, fd, {judgeAnswer: fd_content.answer})
          break;
        case 'text':
          this.formData = Object.assign({}, this.formData, fd, {fillAnswers: fd_content})
          break;
        case 'composite':
          this.formData = Object.assign({}, this.formData, fd, {QAnswer: fd_content.answer})
          break
        default: ;
      }
    },
  }
}
</script>

<style>
  .questAddForm-box {
    text-align: left;
  }
  .questAddForm-box .font-blue {
    color: #0366bb;
  }
  .questAddForm-box .mi-width {
    width: 28%;
  }
  .questAddForm-box .mx-width {
    width: 54%;
  }
  .my-btn {
    cursor: pointer;
  }
</style>
